"""
<name>Cox Proportional Hazards</name>
<author>Generated using Widget Maker written by Kyle R. Covington</author>
<description>Performs Cox Proportional Hazards on a collection of data with event times, event status, and a set of grouping variables.  This widget can perform complex comparisons inculding interactions.</description>
<RFunctions>survival:coxph</RFunctions>
<tags>Survival</tags>
<icon>survival.png</icon>
<inputWidgets></inputWidgets>
<outputWidgets>survival_cox_zph, base_summary</outputWidgets>
"""
from OWRpy import * 
import redRGUI, signals 
import libraries.survival.signalClasses.RCoxphFit as rcf
import libraries.base.signalClasses.RVariable as rvar
from libraries.base.qtWidgets.comboBox import comboBox
from libraries.base.qtWidgets.lineEdit import lineEdit
from libraries.base.qtWidgets.widgetBox import widgetBox
from libraries.base.qtWidgets.tabWidget import tabWidget
from libraries.base.qtWidgets.RFormulaEntry import RFormulaEntry
from libraries.base.qtWidgets.textEdit import textEdit


class coxph(OWRpy): 
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.setRvariableNames(["coxph"])
        self.data = {}
         
        self.RFunctionParam_data = ''
        self.inputs.addInput("data", 'Data Table', rvar.RVariable, self.processdata)
        self.outputs.addOutput("coxph Output", 'COXPH Model Fit', rcf.RCoxphFit)
        
        hbox = redRGUI.base.widgetBox(self.controlArea, orientation = 'horizontal')
        lbox = redRGUI.base.widgetBox(hbox)
        box = redRGUI.base.tabWidget(lbox)
        box.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        self.standardTab = box.createTabPage(name = "Standard")
        self.advancedTab = box.createTabPage(name = "Advanced")
        self.RFunctionParamformula =  redRGUI.base.RFormulaEntry(lbox)
        self.survTime = redRGUI.base.comboBox(self.RFunctionParamformula.extrasBox, label = 'Time')
        self.RFunctionParamrobust_lineEdit =  redRGUI.base.lineEdit(self.standardTab,  label = "robust:", text = 'FALSE')
        self.RFunctionParamweights_lineEdit =  redRGUI.base.lineEdit(self.standardTab,  label = "weights:", text = '')
        
        self.RFunctionParamy_lineEdit =  redRGUI.base.lineEdit(self.advancedTab,  label = "y:", text = 'TRUE')
        self.RFunctionParamx_lineEdit =  redRGUI.base.lineEdit(self.advancedTab,  label = "x:", text = 'FALSE')
        self.RFunctionParammodel_lineEdit =  redRGUI.base.lineEdit(self.advancedTab,  label = "model:", text = 'FALSE')
        self.RFunctionParammethod_comboBox = redRGUI.base.comboBox(self.standardTab, label = "method:", items = ['efron', 'breslow', 'exact'])
        redRGUI.base.commitButton(self.bottomAreaRight, "Commit", callback = self.commitFunction)
        self.RoutputWindow = redRGUI.base.textEdit(hbox, label = "RoutputWindow")
        self.RoutputWindow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
    def processdata(self, data):
        if not self.require_librarys(["survival"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_data=data.getData()
            colnames = self.R('colnames('+self.RFunctionParam_data+')')
            self.survTime.update(colnames)
            self.RFunctionParamformula.update(colnames)
            self.commitFunction()
    def commitFunction(self):
        if str(self.RFunctionParam_data) == '': return
        if str(self.survTime.currentText())== '': return
        formulaOutput = self.RFunctionParamformula.Formula()
        if not formulaOutput: return
        if str(self.survTime.currentText()) == formulaOutput[0]: return
        if formulaOutput[0] == '' or formulaOutput[1] =='': return
        injection = []
        injection.append('formula = Surv(as.numeric('+str(self.survTime.currentText())+'),'+formulaOutput[0]+')~'+formulaOutput[1])
        if str(self.RFunctionParamrobust_lineEdit.text()) != '':
            string = 'robust='+str(self.RFunctionParamrobust_lineEdit.text())
            injection.append(string)
        if str(self.RFunctionParamweights_lineEdit.text()) != '':
            string = 'weights='+str(self.RFunctionParamweights_lineEdit.text())
            injection.append(string)
        if str(self.RFunctionParamy_lineEdit.text()) != '':
            string = 'y='+str(self.RFunctionParamy_lineEdit.text())
            injection.append(string)
        if str(self.RFunctionParamx_lineEdit.text()) != '':
            string = 'x='+str(self.RFunctionParamx_lineEdit.text())
            injection.append(string)
        if str(self.RFunctionParammodel_lineEdit.text()) != '':
            string = 'model='+str(self.RFunctionParammodel_lineEdit.text())
            injection.append(string)
        if str(self.RFunctionParammethod_comboBox.currentText()) != '':
            string = 'method=\''+str(self.RFunctionParammethod_comboBox.currentText())+'\''
            injection.append(string)
        inj = ','.join(injection)
        self.R(self.Rvariables['coxph']+'<-coxph(data='+str(self.RFunctionParam_data)+','+inj+')', wantType = 'NoConversion')
        self.R('txt<-capture.output('+self.Rvariables['coxph']+')', wantType = 'NoConversion')
        self.RoutputWindow.clear()
        tmp = self.R('paste(txt, collapse ="\n")')
        self.RoutputWindow.insertHtml('<br><pre>'+tmp+'</pre>')
        newData = rcf.RCoxphFit(self, data = self.Rvariables['coxph'])
        self.rSend("coxph Output", newData)

